package com.ljk.util.servlet;

import com.ljk.constant.Constant;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;


public class HttpServletUtil {

    static final String IE = "MSIE";
    static final String FIREFOX = "Firefox";
    static final String CHROME = "Chrome";


    /**
     * 是否为http(s)://开头
     *
     * @param link 链接
     * @return 结果
     */
    public static boolean ishttp(String link) {
        return StringUtils.startsWithAny(link, Constant.HTTP, Constant.HTTPS);
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains(IE)) {
            // IE浏览器
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.name());
            filename = filename.replace("+", " ");
        } else {
            if (agent.contains(FIREFOX)) {
                // 火狐浏览器
                filename = new String(fileName.getBytes(), StandardCharsets.ISO_8859_1);
            } else {
                if (agent.contains(CHROME)) {
                    // google浏览器
                    filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.name());
                } else {
                    // 其它浏览器
                    filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.name());
                }
            }
        }
        return filename;
    }

    /**
     * 下载文件名重新编码
     *
     * @param response     响应对象
     * @param realFileName 真实文件名
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);

        response.setHeader("Content-disposition", contentDispositionValue.toString());
    }


    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.name());
        return encode.replaceAll("\\+", "%20");
    }


}
